package com.application.job;

import com.application.model.Global;
import com.application.model.JobLog;
import com.application.model.Order;
import com.application.module.course.Course;
import com.application.util.SendEmailUtil;
import com.jfinal.ext.util.DateUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.platform.mvc.base.BaseService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;

@Deprecated
public class TeacherIncomeReportJob implements Job {

    private ScheduledExecutorService service;
    private static final Log log = Log.getLog(TeacherIncomeReportJob.class);

    public void start() {
        new ConfirmReceiveExecutor("TeacherIncomeReportJob").run();
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        new ConfirmReceiveExecutor("TeacherIncomeReportJob").run();
    }

    class ConfirmReceiveExecutor implements Runnable {

        private String jobName;

        ConfirmReceiveExecutor(String jobName) {
            this.jobName = jobName;
        }

        @Override
        public void run() {

            String s1 = "select teacher_id,email from t_course a left join pt_user b on a.teacher_id = b.id where a.delete_time is null group by teacher_id, email ";
            String sql = "SELECT course_name, total_num, total_amount from t_course c left join\n" +
                    "(select module_id, count(1) as total_num, sum(pay_amount) as total_amount from t_order t \n" +
                    "where delete_time is null and t.order_type = ? and pay_time > ? and pay_time < ? group by module_id) t\n" +
                    "on c.id = t.module_id\n" +
                    "where c.teacher_id = ?";

            List<Course> courses = Course.dao.find(s1);
            String t1 = DateUtil.getWeekStart();
            String t2 = DateUtil.getWeekEnd();

            String subject = "课程收益周报(" + t1 + "至" + t2 + ")";
            List<Integer> failedIds = new ArrayList<>();

            //获取邮箱发送的code
            String mailHost = Global.cacheGetByCode(Global.Code.mail_host).getValue();
            String userName = Global.cacheGetByCode(Global.Code.mail_userName).getValue();
            String authCode = Global.cacheGetByCode(Global.Code.mail_authCode).getValue();

            for (Course cours : courses) {
                String email = cours.get("email");
                List<Record> recordList = Db.find(sql, Order.TYPE_COURSE, t1, t2);

                BigDecimal totalAmount = new BigDecimal("0");
                for (Record record : recordList) {
                    BigDecimal de = record.getBigDecimal("total_amount");
                    if (de != null) {
                        totalAmount = totalAmount.add(de);
                    }
                }

                BigDecimal totalNum = new BigDecimal("0");
                for (Record record : recordList) {
                    BigDecimal de = record.getBigDecimal("total_num");
                    if (de != null) {
                        totalNum = totalNum.add(de);
                    }
                }

                Map<String, Object> map = new HashMap<>();
                map.put("list", recordList);
                map.put("date1", t1);
                map.put("date2", t2);
                map.put("totalNum", totalNum);
                map.put("totalAmount", totalAmount);

                String html = BaseService.getSqlByBeetl("app.reportHtml.sendMailTemplate", map);
                try {
                    if(StrKit.notBlank(email)) {
                        SendEmailUtil.send(mailHost, authCode, userName, subject, html, email);
                    }
                    log.info("#######=> " + html);
                } catch (Exception e) {
                    e.printStackTrace();
//                    failedIds.add(cours.getTeacher_id());
                }
            }


            JobLog log = new JobLog();
            log.setTotal(courses.size());
            log.setJobname(jobName);
            log.setJobclass(this.getClass().getName());
            log.setFailed(failedIds.size());
            if (failedIds.size() > 0) {
                log.setErrorids(failedIds.toString());
            }
            log.setCreateat(new Timestamp(System.currentTimeMillis()));
            log.save();

            System.out.println(jobName + " is over");

            if (service != null) {
                service.shutdown();
            }
        }

    }


    public static void main(String[] args) {
        System.out.println("start:" + System.currentTimeMillis());
        new TeacherIncomeReportJob().start();
        System.out.println("end:" + System.currentTimeMillis());
    }

}